<template>
  <!-- 选项 -->
  <div class="questions-item">
    <!-- "1"表示题型为单选;"2"表示题型为多选 -->
    <el-radio  v-if="questionType === '1'" :label="option.code"></el-radio>
    <el-checkbox v-if="questionType === '2'" :label="option.code"></el-checkbox>
    <el-input v-model="option.title"></el-input>
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :before-upload="handleUpload"
      >
      <!-- 选择图片后,显示图片 -->
      <el-image class="avatar" v-if="option.img" :src="option.img"></el-image>
      <!-- 未选择图片,默认为+图标 -->
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <!-- 点右上角X清除图像 -->
      <i class="el-icon-circle-close avatar-close-icon" @click.stop="handleClearImg"></i>
    </el-upload>
    <!-- 删除某个选项(判断条件idx > 3表示从第5个多选框(索引为4)开始添加删除按钮) -->
    <el-button type="danger" icon="el-icon-delete" size="mini" circle class="option-delete" @click="handleDel" v-if="idx > 3"></el-button>
  </div>
</template>

<script>
export default {
  name: 'questions-option',
  props: ['questionType', 'value', 'idx'], // 父组件传递参数:questionType:问题类型, value:选项对象, idx:选项索引
  data () {
    return {
      option: { ...this.value } // 该组件中声明变量接收父组件选项对象
    }
  },
  watch: {
    // 监听选项对象变化
    value: {
      deep: true,
      handler () {
        this.option = { ...this.value }
      } 
    },
    // 监听选项标题变化
    'option.title' () {
      this.$emit('input', this.option)
    },
    // 监听选项图像变化
    'option.img' () {
      this.$emit('input', this.option)
    }
  },
  methods: {
    // 上传文件时生成临时路径
    handleUpload (file) {
      const url = URL.createObjectURL(file)
      this.option.img = url
    },

    // 点击图片的X按钮清空文件
    handleClearImg () {
      this.option.img = ''
    },

    // 点击删除某个选项
    handleDel () {
      this.$emit('deloption')
    }
  }
}
</script>

<style lang="scss" scoped>
.questions-item {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
}
::v-deep .el-radio, ::v-deep .el-input--medium, ::v-deep .el-checkbox, .avatar-uploader {
  margin-right: 10px;
}
::v-deep .avatar-uploader {
  text-align: center;
}
::v-deep .avatar-uploader .el-upload {
  position: relative;
  width: 100px;
  height: 50px;
  line-height: 50px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  vertical-align: middle;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #a7abaf;
}
.avatar {
  width: 100px;
  height: 50px;
  border-radius: 6px;
}
.avatar-uploader-icon {
  line-height: 50px;
  font-size: 20px;
  color: #8c939d;
}
.avatar-close-icon {
  position: absolute;
  top: -7px;
  right: -7px;
  font-size: 18px;
  color: #8c939d;
  background-color: #fff;
}
.option-delete {
  position: absolute;
  right: -35px;
}
</style>
